/*

 * Copyright (c) 2017-2018, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package of.hotswapinject.plugin.imp;

import jdk.nashorn.internal.runtime.Context;
import of.hotswapinject.core.common.RuntimeContext;
import of.hotswapinject.core.common.Util;
import of.hotswapinject.core.plugin.IMethodEnterPlugin;
import of.hotswapinject.core.plugin.IMethodExitPlugin;
import of.hotswapinject.core.plugin.IMethodFilter;
import of.hotswapinject.core.plugin.MethodMeta;
import org.apache.commons.cli.Option;

public abstract class MethodFilterBase implements IMethodFilter {
    protected abstract boolean canHandle(String key, MethodMeta adviceAdapter);

    protected abstract boolean hookExitOnException(MethodMeta adviceAdapter);

    @Override
    public IMethodEnterPlugin.ReturnParam onEnter(MethodMeta adviceAdapter, String key, Object[] params) {
        if(canHandle(key, adviceAdapter)) {
            return onEnter(key, params);
        }
        return IMethodEnterPlugin.ReturnParam.none();
    }

    protected abstract IMethodEnterPlugin.ReturnParam onEnter(String key, Object[] params);

    @Override
    public IMethodExitPlugin.ReturnParam onExit(MethodMeta adviceAdapter, int opCode, String key, Object[] params, Object result) {
        if(canHandle(key, adviceAdapter)) {
            if(!hookExitOnException(adviceAdapter) && RuntimeContext.getContext().getPluginQueryable().isException(opCode)) {
                return IMethodExitPlugin.ReturnParam.none();
            }
            return onExit(key, params, result);
        }
        return IMethodExitPlugin.ReturnParam.none();
    }

    protected abstract IMethodExitPlugin.ReturnParam onExit(String key, Object[] params, Object result);
}
